<template>
  <div>
    <Category :disabled="isAddShow"></Category>
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin-top: 30px"
      v-show="!isAddShow"
    >
      <template #header>
        <el-button
          type="primary"
          size="default"
          icon="ele-Plus"
          :disabled="!CG3Id"
          @click="addAttr"
          >添加属性</el-button
        >
      </template>
      <!-- card body -->
      <el-table :data="attrList" border stripe>
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="属性名称" prop="attrName"></el-table-column>
        <el-table-column
          label="属性值名称列表"
          width="500"
          prop="attrValueList"
        >
          <template v-slot="{ row }">
            <el-tag
              style="margin-right: 5px"
              type="danger"
              size="default"
              effect="dark"
              v-for="item in row.attrValueList"
              :key="item.id"
              >{{ item.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              type="warning"
              size="default"
              icon="ele-Edit"
              @click="updateAttr(row)"
            ></el-button>
            <!-- <el-popconfirm
              title="是否确认删除?"
              @confirm="confirmDelete(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  icon="ele-Delete"
                ></el-button>
              </template>
            </el-popconfirm> -->

            <el-button
              type="danger"
              size="default"
              icon="ele-Delete"
              @click="confirmDelete(row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin-top: 30px"
      v-show="isAddShow"
    >
      <el-form label-width="80px" :inline="true">
        <el-form-item label="属性名">
          <el-input v-model="newAttr.attrName" />
        </el-form-item>
      </el-form>
      <div>
        <el-button
          type="primary"
          size="default"
          @click="addAttrValue"
          :disabled="!newAttr.attrName"
          >添加属性值</el-button
        >
        <el-button type="default" size="default" @click="isAddShow = false"
          >取消</el-button
        >
      </div>
      <el-table
        border
        stripe
        style="margin: 20px 0"
        :data="newAttr.attrValueList"
      >
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="属性值名称">
          <template v-slot="{ row, $index }">
            <el-input
              v-if="row.isEdit"
              v-model="row.valueName"
              size="default"
              clearable
              @blur="tolook(row, $index)"
              ref="editEle"
            ></el-input>
            <p v-else @click="toEdit(row)">{{ row.valueName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ $index }">
            <!-- <el-popconfirm title="是否确认删除?" @confirm="delAttrValue($index)">
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  icon="ele-Delete"
                ></el-button>
              </template>
            </el-popconfirm> -->
            <el-button
              type="danger"
              size="default"
              icon="ele-Delete"
              @click="delAttrValue"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="!newAttr.attrName || newAttr.attrValueList.length === 0"
          >保存</el-button
        >
        <el-button type="default" size="default" @click="isAddShow = false"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "Attr",
});
</script>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from "vue";
import { cloneDeep } from "lodash";
import useCGStore from "@/stores/category";
import { ElMessage, ElMessageBox } from "element-plus";
import { storeToRefs } from "pinia";
import {
  reqDeleteAttr,
  reqAddorUpdate,
  reqAttrInfoList,
  type attrListType,
  type attrItemType,
  type attrValueItemType,
} from "@/api/attr";
const CGStore = useCGStore();
const { CG1Id, CG2Id, CG3Id } = storeToRefs(CGStore);
const attrList = ref<attrListType>([]);
// 编辑模式下自动获取焦点
const editEle = ref<HTMLInputElement>();
const getAttrList = async () => {
  try {
    const re = await reqAttrInfoList(
      CG1Id.value as number,
      CG2Id.value as number,
      CG3Id.value as number
    );
    attrList.value = re;
  } catch (e: any) {
    ElMessage.error(e.message);
  }
};
watch(CG3Id, async (newVal) => {
  if (!newVal) {
    attrList.value = [];
    return;
  }
  // 重新请求
  getAttrList();
});
onMounted(() => {
  (CG1Id.value = null), (CG2Id.value = null);
  CG3Id.value = null;
});

// 切换新增和属性列表
const isAddShow = ref(false);

// 收集新增 or 修改的值
const newAttr = ref<attrItemType>({
  attrName: "",
  categoryId: CG3Id.value as number,
  categoryLevel: 3,
  attrValueList: [],
});

// 点击添加属性值
const addAttrValue = () => {
  const newAttrValue: attrValueItemType = {
    valueName: "",
    attrId: newAttr.value.id,
    isEdit: true,
  };
  // 新创建的attrValue的值插入到attr的attrValueList中
  newAttr.value.attrValueList.push(newAttrValue);
  nextTick(() => {
    editEle.value?.focus();
  });
};

// 修改属性
const updateAttr = (row: attrItemType) => {
  isAddShow.value = true;
  newAttr.value = cloneDeep(row);
  // 给每一个属性值对象添加一个isEdit属性,代表当前属性值是编辑模式还是查看模式
  newAttr.value.attrValueList.forEach((item) => {
    item.isEdit = false;
  });
};

// 添加属性
const addAttr = () => {
  isAddShow.value = true;
  newAttr.value = {
    attrName: "",
    categoryId: CG3Id.value as number,
    categoryLevel: 3,
    attrValueList: [],
  };
};

// 点击输入框进入编辑模式
const toEdit = (row: attrValueItemType) => {
  row.isEdit = true;
  nextTick(() => {
    editEle.value?.focus();
  });
};

const tolook = (row: attrValueItemType, index: number) => {
  // 判断为空，直接删除
  if (row.valueName === "") {
    newAttr.value.attrValueList.splice(index, 1);
  }
  // 查看是否有相等数据
  const isValueName = newAttr.value.attrValueList.some((item) => {
    if (item !== row) {
      return item.valueName === row.valueName;
    }
  });
  // 如果有相等，则直接删除
  if (isValueName) {
    newAttr.value.attrValueList.splice(index, 1);
    ElMessage.error("已重复,自动删除");
  }
  row.isEdit = false;
};

// 删除单个属性值的回调函数 (气泡确认)
// const delAttrValue = (index: number) => {
//   newAttr.value.attrValueList.splice(index, 1);
//   ElMessage.success("删除成功")
// };

// 删除单个属性值的回调函数 (弹窗确认)
const delAttrValue = (index: number) => {
  ElMessageBox.confirm("是否删除?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      newAttr.value.attrValueList.splice(index, 1);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 提交新增 or 修改
const save = async () => {
  newAttr.value.attrValueList.forEach((item) => {
    delete item.isEdit;
  });
  //校验属性名 和 属性列表都不能为空
  if (!newAttr.value.attrName || newAttr.value.attrValueList.length === 0) {
    return ElMessage.error("属性名或者属性值列表不能为空");
  }
  try {
    if (newAttr.value.id) {
      await reqAddorUpdate(newAttr.value);
      ElMessage.success("修改成功");
    } else {
      await reqAddorUpdate(newAttr.value);
      ElMessage.success("添加成功");
    }
    // 切换到属性页面
    isAddShow.value = false;
    // 重新请求
    getAttrList();
  } catch (e: any) {
    return ElMessage.error(e);
  }
};

// 删除某个属性的回调函数(气泡弹窗)
// const confirmDelete = async (id: number) => {
//   try {
//     await reqDeleteAttr(id);
//     ElMessage.success("删除成功");
//     //重新请求
//     getAttrList();
//   } catch (e: any) {
//     ElMessage.error(e.message);
//   }
// };

// 删除某个属性的回调函数(普通弹窗)
const confirmDelete = (id: number) => {
  ElMessageBox.confirm("是否删除?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(async () => {
      await reqDeleteAttr(id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getAttrList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
};
</script>

<style scoped></style>
